package com.dmai.capacity.platform.user.service.impl;

import com.dmai.capacity.platform.common.model.LoginAppUser;
import com.dmai.capacity.platform.common.model.SysRole;
import com.dmai.capacity.platform.common.model.SysUser;
import com.dmai.capacity.platform.common.service.IUserBaseService;
import com.dmai.capacity.platform.user.mapper.SysRoleDao;
import com.dmai.capacity.platform.user.mapper.SysUserDao;
import com.dmai.capacity.platform.user.mapper.SysUserRoleDao;
import com.dmai.capacity.platform.user.model.SysFunctionPermission;
import com.dmai.capacity.platform.user.model.SysUserRole;
import com.dmai.capacity.platform.user.service.ISysFunctionPermissionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;


@Slf4j
@Service
public class UserBaseServiceImpl implements IUserBaseService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private SysUserDao userDao;

    @Autowired
    private SysUserRoleDao userRoleDao;

    @Autowired
    private SysRoleDao roleDao;

    @Autowired
    private ISysFunctionPermissionService functionPermissionService;


    @Override
    public LoginAppUser findByUsername(String username) {
        SysUser sysUser = this.selectByUsername(username);
        return getLoginAppUser(sysUser);
    }

    @Override
    public LoginAppUser findByOpenId(String username) {
        SysUser sysUser = this.selectByOpenId(username);
        return getLoginAppUser(sysUser);
    }

    @Override
    public LoginAppUser findByMobile(String phone) {
        SysUser sysUser = this.selectByMobile(phone);
        return getLoginAppUser(sysUser);

    }

    @Override
    public LoginAppUser findByUserId(Long userId) {
        SysUser sysUser = userDao.findById(userId);
        return getLoginAppUser(sysUser);
    }

    /**
     * 根据用户名查询用户
     *
     * @param username
     * @return
     */
    @Override
    public SysUser selectByUsername(String username) {
        SysUser user = userDao.findByUsername(username);
        if (user != null) {
            List<SysUserRole> list = userRoleDao.findByUser(user.getId());
            String roleIds = "";
            Set<SysRole> roles = new HashSet<>();
            if (!CollectionUtils.isEmpty(list)) {
                for (SysUserRole relation : list) {
                    SysRole role = roleDao.findById(relation.getRoleId());
                    roles.add(role);
                    if (roleIds.length() == 0) {
                        roleIds += relation.getRoleId();
                    } else {
                        roleIds += "," + relation.getRoleId();
                    }
                }
                user.setRoleIds(roleIds);
                user.setRoles(roles);
            }
            if (!user.getUsername().equals(username)) {
                user = null;
            }
        }

        return user;

    }

    /**
     * 根据手机号查询用户
     *
     * @param mobile
     * @return
     */
    public SysUser selectByMobile(String mobile) {
        Map<String, Object> param = new HashMap<>();
        param.put("mobile", mobile);
        List<SysUser> users = userDao.findList(param);
        return getUser(users);

    }

    /**
     * 根据openId查询用户
     *
     * @param openId
     * @return
     */
    public SysUser selectByOpenId(String openId) {
        Map<String, Object> param = new HashMap<>();
        param.put("openId", openId);
        List<SysUser> users = userDao.findList(param);
        return getUser(users);
    }


    private SysUser getUser(List<SysUser> users) {
        SysUser user = null;
        if (users != null && !users.isEmpty()) {
            user = users.get(0);
        }
        return user;
    }


    public LoginAppUser getLoginAppUser(SysUser sysUser) {
        if (sysUser != null) {
            LoginAppUser loginAppUser = new LoginAppUser();
            loginAppUser.setId(sysUser.getId());
            loginAppUser.setUsername(sysUser.getUsername());
            loginAppUser.setRealname(sysUser.getRealname());
            loginAppUser.setMobile(sysUser.getMobile());
            loginAppUser.setType(sysUser.getType());
            loginAppUser.setStatus(sysUser.getStatus());
            loginAppUser.setOrganizationId(sysUser.getOrganizationId());
            loginAppUser.setCreateTime(sysUser.getCreateTime());
            loginAppUser.setDescription(sysUser.getDescription());
            loginAppUser.setEmail(sysUser.getEmail());
            loginAppUser.setDeleted(sysUser.getDeleted());
            loginAppUser.setHeadImgUrl(sysUser.getHeadImgUrl());
            loginAppUser.setPassword(sysUser.getPassword());
            loginAppUser.setEnabled(sysUser.getEnabled());
            loginAppUser.setTenantId(sysUser.getTenantId());

            loginAppUser.setRoleIds(sysUser.getRoleIds());
            loginAppUser.setRoles(sysUser.getRoles());

            HashSet permissions = new HashSet();
            List<SysFunctionPermission> scopePermissionList = functionPermissionService.findByUser(loginAppUser);
            if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(scopePermissionList)) {
                for (SysFunctionPermission item : scopePermissionList) {
                    permissions.add(item.getItem().getCode());
                }
            }

            loginAppUser.setPermissions(permissions);
            return loginAppUser;
        }
        return null;
    }
}